package com.shopx.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author:lituo
 * @date:2022/4/9
 **/
@Slf4j
public class QRCodeUtil {
  /**
   * 生成二维码
   *
   * @param text 内容，可以是链接或者文本
   * @param path 生成的二维码位置
   */
  public static void encodeQRCode(String text, String path) {
    encodeQRCode(text, path, null, null, null);
  }

  /**
   * TODO
   *
   * @param text
   * @param path
   * @param width
   * @param height
   * @param format
   * @return void
   * @author lituo
   * @date 9:21 上午 2022/4/9
   */
  public static void encodeQRCode(String text, String path, Integer width, Integer height, String format) {
    try {
      // 得到文件对象
      File file = new File(path);
      // 判断目标文件所在的目录是否存在
      if (!file.getParentFile().exists()) {
        if (!file.getParentFile().mkdirs()) {
          return;
        }
      }
      // 宽
      if (width == null) {
        width = 300;
      }
      // 高
      if (height == null) {
        height = 300;
      }
      // 图片格式
      if (format == null) {
        format = "png";
      }

      // 设置字符集编码
      Map<EncodeHintType, Object> hints = new HashMap<>();
      hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
      // 生成二维码矩阵
      BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
      // 二维码路径
      Path outputPath = Paths.get(path);
      // 写入文件
      MatrixToImageWriter.writeToPath(bitMatrix, format, outputPath);
    } catch (Exception e) {
      log.error("encodeQRCode.error.",e);
      throw new RuntimeException("二维码生成失败");
    }
  }


  /**
   * 解析二维码
   *
   * @return com.alibaba.fastjson.JSONObject
   * @author lituo
   * @date 9:23 上午 2022/4/9
   * @param  filePath
   */
  public static JSONObject decodeQRCode(String filePath) {
    try {

      // 读取图片
      BufferedImage image = ImageIO.read(new File(filePath));

      // 多步解析
      LuminanceSource source = new BufferedImageLuminanceSource(image);
      Binarizer binarizer = new HybridBinarizer(source);
      BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

      // 一步到位
      // BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)))

      // 设置字符集编码
      Map<DecodeHintType, String> hints = new HashMap<>();
      hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
      // 对图像进行解码
      Result result = new MultiFormatReader().decode(binaryBitmap, hints);
      // 解码内容
      JSONObject content = JSONObject.parseObject(result.getText());
      return content;
    } catch (Exception e) {
      log.error("decodeQRCode，error.", e);
      throw new RuntimeException("解析二维码失败");
    }
  }

  public static void main(String args[]){
    QRCodeUtil.encodeQRCode("http://192.168.1.100:8080/mng/login.html","/Volumes/BACK/temp/hello.png");
  }

}
